import random

from django.shortcuts import render

# Create your views here.
import logging

from common.constant.redis_constant import VERIF_CODES, VERB_PHONE, SMS_RECODE
from common.responses.r import R
from common.responses.result import Result
from libs.ronglian_sms import send_sms
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from meiduo_mall.celery_tasks.sms import tasks

log = logging.getLogger("django")


# Create your views here.

class Index(APIView):
    def get(self, request):
        print("hello")
        return Response({"message": "hello"})


# 获取验证码
class getSmsCodeView(APIView):

    def get(self, request, mobile):
        # 获取缓存中当前手机号是否已经在60秒内发过验证码
        redis_str = get_redis_connection(VERIF_CODES)
        res = redis_str.get(SMS_RECODE % mobile)
        if res:
            return Result.set_sys_error("已发送过验证码，请等待60秒")

        # 生成验证码
        code = "%04d" % random.randint(0, 9999)
        # redis管道 作用是记录执行命令统一执行
        pl = redis_str.pipeline()
        # 保存验证码信息同时记录当前手机号
        pl.setex(VERB_PHONE % mobile, 300, code)
        # 以发送标识
        pl.setex(SMS_RECODE % mobile, 60, "Y")
        # 发送短信 {"statusCode":"112310","statusMsg":"【短信】应用未上线，模板短信接收号码外呼受限"}
        # resp = send_sms(mobile, (code, 5))
        # log.info(resp)
        pl.execute()
        # log.info(f"验证码生成成功：{code}，有效期5分钟")
        # 异步发送验证码
        tasks.send_sms.delay(mobile, code)

        return Result.ok()
